package com.coding.v1;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * @description <获取数据库表信息>
 * @author: <chancezhou>
 * @Date: 2023/7/26 10:38
 */
public class getTableMetaInfo {


    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "root123";
        String tableName = "t_user";

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            DatabaseMetaData metaData = connection.getMetaData();

            // 获取数据库名称
            String databaseName = metaData.getDatabaseProductName();
            System.out.println("数据库名称：" + databaseName);

            // 获取数据库版本
            String databaseVersion = metaData.getDatabaseProductVersion();
            System.out.println("数据库版本：" + databaseVersion);

            // 获取数据库中的表信息
            String catalog = null;
            String schemaPattern = null;
            String tableNamePattern = tableName;
            String[] types = {"TABLE"};
            ResultSet tables = metaData.getTables(catalog, schemaPattern, tableNamePattern, types);

            while (tables.next()) {
//                String tableName = tables.getString("TABLE_NAME");
                String foundTableName = tables.getString("TABLE_NAME");
                System.out.println("表名：" + foundTableName);

                // 获取表中的列信息
                ResultSet columns = metaData.getColumns(catalog, schemaPattern, tableName, null);

                while (columns.next()) {
                    String columnName = columns.getString("COLUMN_NAME");
                    String columnType = columns.getString("TYPE_NAME");
                    int columnSize = columns.getInt("COLUMN_SIZE");
                    System.out.println("列名：" + columnName + ", 类型：" + columnType + ", 大小：" + columnSize);
                }

                columns.close();
            }

            tables.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
